package mi.payment.utils.transaction;

import android.content.Context;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

import mi.payment.constants.TransactionBitmap;
import mi.payment.utils.iso8583.EncodePackage;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.secure.TerminalSecure;

/**
 * @author lj on 2017/2/17.
 */
public class KEKDownloadTask extends TransactionTask<Void, Void, String> {

    protected KEKDownloadTask(Context context) {
        super(context, false);
    }

    @Override
    protected void onBegin(Void[] params) {
    }

    @Override
    protected String appointResult() {
        return resultStr;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return EncodePackage.preAssemblyBase(TransactionBitmap.BITMAP_KEK_DOWNLOADED);
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        MsgField f041 = fieldMap.get("F041");
        f041.setDataStr(merManagerSettings.getTerminalNum());

        MsgField f042 = fieldMap.get("F042");
        f042.setDataStr(merManagerSettings.getMerchantNum());

        MsgField f060 = fieldMap.get("F060");
        f060.setDataStr("00" + mSystemParamsSettings.getBatchNumStart() + "592");
        f060.setDataLength(11);

        MsgField f062 = fieldMap.get("F062");
        f062.setDataStr("Sequence No176900SN20160900149");
        f062.setDataLength(30);

        return EncodePackage.assembly(fieldMap, "0800", TerminalSecure.PROCESSREQUEST_NONE);
    }

    @Override
    protected void onUnpacked(HashMap<String, MsgField> resp) {
        MsgField f039 = resp.get("F039");
        String ret = "";
        if (f039 != null) {
            ret = resp.get("F039").getDataStr();
        }
        if (TextUtils.equals("00", ret)) {
            MsgField f062_r = resp.get("F062");
            if (f062_r != null) {
                ret = f062_r.getDataStr();
                // 保存工作密钥
                // int r = TerminalSecure.saveKEK(f062_r.getDataStr());
            }
        }
        resultStr = ret;
    }


}
